package com.starblink.login.createaccount.inputemail.ui

import com.alibaba.android.arouter.facade.annotation.Route
import com.starblink.basic.route.RoutePage
import com.starblink.android.basic.base.activity.BaseTVMActivity
import android.os.Bundle
import android.view.View
import com.starblink.android.basic.extension.navigation
import com.starblink.android.basic.user.login.LoginManager
import com.starblink.basic.util.CommUtils
import com.starblink.basic.util.KeyboardUtils
import com.starblink.login.createaccount.inputpsw.ui.CreateAccountInputPswActivity
import com.starblink.login.databinding.ActivityCreateAccountInputEmailBinding

/**
 * 创建账户-输入邮箱
 */
@Route(path = RoutePage.Login.CREATE_ACCOUNT_INPUT_EMAIL)
class CreateAccountInputEmailActivity :
    BaseTVMActivity<ActivityCreateAccountInputEmailBinding, CreateAccountInputEmailVM>() {

    override fun initViewBinding(): ActivityCreateAccountInputEmailBinding =
        ActivityCreateAccountInputEmailBinding.inflate(layoutInflater)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        viewBinding.etEmail.setOnEditInputListener {
            viewBinding.tvErrorHint.visibility = View.GONE
            viewBinding.btnContinue.isEnabled = !it.isEmpty()
        }

        viewBinding.btnContinue.isEnabled = viewBinding.etEmail.text.isNotEmpty()
        viewBinding.btnContinue.setOnClickListener {
            val res = LoginManager.validateEmail(viewBinding.etEmail.text)
            if (res == null) {
                // 输入邮箱OK，接口验证
                viewModel.checkEmailExist(viewBinding.etEmail.text)
            } else {
                viewBinding.tvErrorHint.visibility = View.VISIBLE
                viewBinding.tvErrorHint.text = res
            }
        }

        viewModel.checkResultLiveData.observe(this) {
            if (it) {
                // it==true，表示账号已存在，邮箱已被使用
                viewBinding.tvErrorHint.visibility = View.VISIBLE
                viewBinding.tvErrorHint.text = CommUtils.getString(com.starblink.basic.style.R.string.login_email_exist)
                return@observe
            }

            mActivity.navigation(
                RoutePage.Login.CREATE_ACCOUNT_INPUT_PSW,
                Bundle().apply {
                    putString(CreateAccountInputPswActivity.EXTRA_EMAIL, viewBinding.etEmail.text.trim())
                })
        }

        //默认显示软键盘
        KeyboardUtils.openSoftKeyboard(this, viewBinding.etEmail.editText)
    }
}